package com.epam.weblibrary.entities.user;

import com.epam.weblibrary.entities.order.Order;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;

@Entity
@Data
@NoArgsConstructor
public class User implements UserDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Length(min = 1, max = 10, message = "Login must be within 1 and 10 letters")
    private String login;

    @Length(min = 1, max = 15, message = "Password must be within 1 and 15 letters")
    private String password;

    @Enumerated(EnumType.STRING)
    private Roles role;

    @Length(min = 1, max = 20, message = "First name must be within 1 and 20 letters")
    private String firstName;

    @Length(min = 1, max = 20, message = "Last name must be within 1 and 20 letters")
    private String lastName;

    @Email(message = "Email is not correct")
    private String email;

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private List<Order> orders;

    private float discount;
    private int booksTaken;

    public User(String login, String password, String first_name, String last_name, String email) {
        this.login = login;
        this.password = password;
        this.firstName = first_name;
        this.lastName = last_name;
        this.email = email;
    }

    public User(String login, String password, String first_name, String last_name, String email, Roles role) {
        this.login = login;
        this.password = password;
        this.firstName = first_name;
        this.lastName = last_name;
        this.email = email;
        this.role = role;
    }

    public void addTakenBook() {
        booksTaken++;
    }

    public void addOrder(Order order) {
        this.orders.add(order);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new LinkedList();
        authorities.add(new SimpleGrantedAuthority(role.toString()));
        return authorities;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return login;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}